package com.dvg.http;

import java.util.Vector;

import com.dvg.comms.CommsListener;
import com.dvg.comms.CommsManager;

public class HttpCore implements CommsListener {
	public static final int REQUEST_METHOD_GET 		= 1;
	public static final int REQUEST_METHOD_POST 	= 2;
	
	private int _requestMethod;
	
	private final String _baseUrl = "http://vincent.0fees.net/";
	private String _connectionParameter;
	private String _targetScript;
	
	private IHttpCallback _listener;
	
	private Vector _urlParameters;
	
	public HttpCore(){
		this._requestMethod = HttpCore.REQUEST_METHOD_GET;
		this._urlParameters = new Vector();
		this._connectionParameter = "";
		this._targetScript = "";
	}
	
	public HttpCore(IHttpCallback listener){
		this._requestMethod = HttpCore.REQUEST_METHOD_GET;
		this._listener = listener;
		this._urlParameters = new Vector();
		this._connectionParameter = "";
		this._targetScript = "";
	}
	
	public void setCallbackListener(IHttpCallback listener){
		this._listener = listener;
	}

	public void notifyCommsError(int errorCode) {
		// TODO Auto-generated method stub
		
	}

	public void notifyCommsSuccess(byte[] data) {
		this._listener.notifySuxcess(data);
	}
	
	
	public void processRequest(){
		String url = this.buildUrl();
		CommsManager.getInstance().getDataAndCallback(url, this);
	}

	public void set_requestMethod(int requestMethod) {
		this._requestMethod = requestMethod;
	}

	public void set_connectionParameter(String connectionParameter) {
		this._connectionParameter = connectionParameter;
	}

	public void set_urlParameters(Vector urlParameters) {
		this._urlParameters = urlParameters;
	}
	
	public void set_targetScript(String targetScript) {
		this._targetScript = targetScript;
	}

	private String buildUrl() {
		String resultUrl = this._baseUrl + this._targetScript;
		if (this._urlParameters.isEmpty() || this._requestMethod == HttpCore.REQUEST_METHOD_POST)
			return resultUrl;
		
		resultUrl += "?";
		int paramsCount = this._urlParameters.size();
		for (int i = 0; i < paramsCount; i++) {
			resultUrl += ((UrlParameter)this._urlParameters.elementAt(i)).toString();
			resultUrl += "&";
		}
		
		return resultUrl.substring(0, resultUrl.lastIndexOf('&')) + this._connectionParameter;
	}
}
